package com.imooc.mall.controller;

import com.github.pagehelper.PageInfo;
import com.imooc.mall.common.ApiRestResponse;
import com.imooc.mall.common.Constant;
import com.imooc.mall.exception.ImoocMallException;
import com.imooc.mall.exception.ImoocMallExceptionEnum;
import com.imooc.mall.model.pojo.Product;
import com.imooc.mall.model.request.AddProductAdd;
import com.imooc.mall.model.request.UpdateProduct;
import com.imooc.mall.service.ProductService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.UUID;

@Controller
public class ProductController {
    @Autowired
    private ProductService productService;

    @PostMapping("/admin/product/add")
    @ResponseBody
    public ApiRestResponse AddProduct(@RequestBody @Valid AddProductAdd addProductAdd ){
        productService.AddProductAdd(addProductAdd);
        return ApiRestResponse.success();
    }


    @PostMapping("/admin/upload/file")
    @ResponseBody
    public ApiRestResponse upload(HttpServletRequest httpServletRequest, @RequestParam("file")MultipartFile file){
        String filename = file.getOriginalFilename();
        // 获取后缀的
        String suffixName = filename.substring(filename.lastIndexOf("."));
        //生成随机数字的UUID
        UUID uuid = UUID.randomUUID();
        // 生成新的文件名字
        String newFileName = uuid.toString() + suffixName;

        //创建文件夹
        File fileDirectory = new File(Constant.FILE_UPLOAD_DIR);
        // 路径名
        File destFile = new File(Constant.FILE_UPLOAD_DIR + newFileName);
        if (!fileDirectory.exists()){
            if (!fileDirectory.mkdir()) {
                throw new ImoocMallException(ImoocMallExceptionEnum.MKDIR_FAILED);
            }
        }
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 把文件从请求放到本地的地址了

        //从本地中返回回去。
        try {
            // string stringbuffie
            return ApiRestResponse.success(getHost(new URI(httpServletRequest.getRequestURL()+""))+
                    "/images/"+newFileName);

        } catch (URISyntaxException e) {
            return ApiRestResponse.error(ImoocMallExceptionEnum.UPLOAD_FAILED);
        }
    }

    private URI getHost(URI uri){
        // 只要获取需要的URL地址
        URI effectiveURI ;
        try {
            // getScheme 获取协议的信息
            effectiveURI = new URI(uri.getScheme(),
                    uri.getUserInfo(),uri.getHost(),
                    uri.getPort(),null,null,null);
        } catch (URISyntaxException e) {
           effectiveURI = null;
        }
        return effectiveURI;
    }


    @ApiOperation("商品更新目录")
    @PostMapping("/admin/product/update")
    @ResponseBody
    public ApiRestResponse UpdateProduct(@RequestBody @Valid UpdateProduct updateProduct){
        Product product = new Product();
        BeanUtils.copyProperties(updateProduct,product);
        productService.UpdateProduct(product);
        return ApiRestResponse.success();
    }

    @ApiOperation("后台删除的功能")
    @PostMapping("/admin/product/delete")
    @ResponseBody
    public ApiRestResponse delete(@RequestParam Integer id){
        productService.DeleteProduct(id);
        return ApiRestResponse.success();
    }


    @ApiOperation("后台批量上下架功能")
    @ResponseBody
    @PostMapping("admin/product/batchUpdateSellStatus")
    public ApiRestResponse batchUpdateSellStatus(@RequestParam Integer[] ids  ,@RequestParam Integer Status ){
        productService.BatchUpdateSellStatus(ids, Status);
        return ApiRestResponse.success();
    }



    @GetMapping("/admin/product/list")
    @ResponseBody
    public ApiRestResponse list(@RequestParam("PageSize") Integer pageSize , @RequestParam("pageNum") Integer pageNum){
        PageInfo list = productService.listAdmin(pageSize, pageNum);
        return ApiRestResponse.success(list);
    }
}